package boot

import (
	"github.com/gogf/gcache-adapter/adapter"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/os/gsession"
	"github.com/gogf/gf/util/gmode"
	"net/http"
	"time"
)

func init() {
	s := g.Server()
	statusHandle(s)
	initSessions(s)
	initRedisCache()
	if gmode.IsDevelop() {
		s.BindHookHandler("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) {
			r.Response.Header().Set("Cache-Control", "no-store")
		})
	}
}

// initRedisCache 初始化Redis缓存
func initRedisCache() {
	cache := gcache.New()
	redis := adapter.NewRedis(g.Redis())
	// 全局缓存
	cache.SetAdapter(redis)
	// 数据库缓存
	g.DB().GetCache().SetAdapter(redis)
}

// initSessions 初始化session配置
func initSessions(s *ghttp.Server) {
	sessionStorage := g.Config().Get("server.session.sessionStorage")
	if sessionStorage == "redis" {
		err := s.SetConfigWithMap(g.Map{
			"SessionIdName":  g.Config().Get("server.SessionIdName"),
			"SessionStorage": gsession.NewStorageRedis(g.Redis()),
			"SessionMaxAge":  15 * time.Minute,
		})
		if err != nil {
			panic(err)
		}
	} else if sessionStorage == "memory" {
		err := s.SetConfigWithMap(g.Map{
			"SessionStorage": gsession.NewStorageMemory(),
		})
		if err != nil {
			panic(err)
		}
	}
}

func statusHandle(s *ghttp.Server) {
	// 前台系统自定义错误页面
	s.BindStatusHandler(http.StatusUnauthorized, func(r *ghttp.Request) {

	})
	s.BindStatusHandler(http.StatusForbidden, func(r *ghttp.Request) {

	})
	s.BindStatusHandler(http.StatusNotFound, func(r *ghttp.Request) {

	})
	s.BindStatusHandler(http.StatusInternalServerError, func(r *ghttp.Request) {

	})
}
